﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.UI;

namespace PhotoZoon.Dal
{
    public class Thumbnail
    {
        /// <summary>
        /// 创建单个文件的缩略图
        /// </summary>
        /// <param name="originalImagePath">原图路径</param>
        /// <param name="thumbnailPath">缩略图路径</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">缩略图模式</param>
        /// <returns>bool</returns>
        public static bool Create(string originalImagePath, string thumbnailPath, int width, int height, string mode, string[] phototype, bool IsForce)
        {
            if (File.Exists(thumbnailPath)&&!IsForce)
            {
                FileInfo ThumbnailImageInfo = new FileInfo(thumbnailPath);
                if (ThumbnailImageInfo.Length>0) return false;
            }

            FileInfo originalImageInfo = new FileInfo(originalImagePath);
            string[] strSpil = originalImageInfo.Name.Split('.');//将此地址用.号进行分割(img/1.jpg)
            string strEnd = strSpil[strSpil.Length - 1].ToLower();//得到后面得jpg
            string[] strPic = phototype;//定义一个数组里面放文件格式
            ArrayList arry = new ArrayList();
            arry.AddRange(strPic); //定义一个可变数组，用于放文件格式
            if (!arry.Contains(strEnd))
            {
                return false;
            }

            System.Drawing.Image originalImage;
            try
            {
                originalImage = System.Drawing.Image.FromFile(originalImagePath);
            }
            catch (OutOfMemoryException)
            {
                return false;
            }
            if (originalImage.Width <= 0 || originalImage.Height <= 0) return false;

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形） 
                    break;
                case "W"://指定宽，高按比例 
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形） 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case "DB"://等比缩放（不变形，如果高大按高，宽大按宽缩放） 
                    if ((double)originalImage.Width / (double)towidth < (double)originalImage.Height / (double)toheight)
                    {
                        if (originalImage.Height <= height)
                        {
                            toheight = originalImage.Height;
                            towidth = originalImage.Width;
                        }
                        else
                        {
                            toheight = height;
                            towidth = originalImage.Width * height / originalImage.Height;
                        }
                    }
                    else
                    {
                        if (originalImage.Width <= width)
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                        else
                        {
                            towidth = width;
                            toheight = originalImage.Height * width / originalImage.Width;
                        }
                    }
                    break;
                default:
                    break;
            }

            System.Drawing.Image bitmap;
            System.Drawing.Graphics g;

            try
            {
                //新建一个bmp图片
                bitmap = new System.Drawing.Bitmap(towidth, toheight);

                //新建一个画板
                g = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                g.Clear(System.Drawing.Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            }
            catch (Exception)
            {
                return false;
            }

            try
            {
                //保存缩略图
                if (originalImagePath.ToUpper().EndsWith("JPG"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else if (originalImagePath.ToUpper().EndsWith("BMP"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                }
                else if (originalImagePath.ToUpper().EndsWith("GIF"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                }
                else if (originalImagePath.ToUpper().EndsWith("PNG"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                }
                else if (originalImagePath.ToUpper().EndsWith("EMF"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Emf);
                }
                else if (originalImagePath.ToUpper().EndsWith("EXIF"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Exif);
                }
                else if (originalImagePath.ToUpper().EndsWith("ICO"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Icon);
                }
                else if (originalImagePath.ToUpper().EndsWith("TIFF"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Tiff);
                }
                else if (originalImagePath.ToUpper().EndsWith("WMF"))
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Wmf);
                }
                else
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

            return true;
        }

        /// <summary>
        /// 创建目录的缩略图
        /// </summary>
        /// <param name="originalImagePath">原图目录</param>
        /// <param name="thumbnailPath">缩略图目录</param>
        /// <param name="width">缩略图高度</param>
        /// <param name="height">缩略图宽度</param>
        /// <param name="mode">缩略图模式</param>
        /// <param name="IsSubDir">是否目录</param>
        /// <returns>bool</returns>
        public static bool Create(string originalImagePath, string thumbnailPath, int width, int height, string mode, string[] phototype, bool IsForce, bool IsSubDir, bool IsOutPic)
        {
            string thumbnailPhysicalPath = new Page().Server.MapPath(thumbnailPath);
            if (!Directory.Exists(thumbnailPhysicalPath)) Directory.CreateDirectory(thumbnailPhysicalPath);

            DataTable dt = PhotoList.Dal.IO.GetFilesDataTable(originalImagePath);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string OriginalFullPath = originalImagePath + @"\" + dt.Rows[i]["name"].ToString();
                string ThumbnailFullPath = thumbnailPath + @"\" + dt.Rows[i]["name"].ToString();
                if (!File.Exists(OriginalFullPath)) Create(new Page().Server.MapPath(OriginalFullPath), new Page().Server.MapPath(ThumbnailFullPath), width, height, mode, phototype, IsForce);
            }

            if (IsSubDir)
            {
                DataTable subdt = PhotoList.Dal.IO.GetDirectoriesDataTable(originalImagePath, 10);
                for (int j = 0; j < subdt.Rows.Count; j++)
                {
                    string OriginalFullDirectory = originalImagePath + @"\" + subdt.Rows[j]["name"].ToString();
                    string ThumbnailFullDirectory = thumbnailPath + @"\" + subdt.Rows[j]["name"].ToString();
                }
            }

            return true;
        }
    }
}
